package com.shenhaofeng.app.component;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;

import com.shenhaofeng.app.log.AppLog;

import java.util.ArrayList;
import java.util.List;


/**
 * Activity管理器,管理activity栈
 * Created by Administrator on 2016/8/28.
 */
public class ActivityLifecycleManager {

    private static final String TAG = "ActivityLifecycleManager";

    private static final ActivityLifecycleManager ACTIVITY_LIFECYCLE_MANAGER = new ActivityLifecycleManager();

    private ActivityLifecycleCallbacksImpl mActivityLifecycleCallbacks = new ActivityLifecycleCallbacksImpl();

    private boolean isInit = false;

    private static boolean isDebug = false;


    public static ActivityLifecycleManager get() {
        return ACTIVITY_LIFECYCLE_MANAGER;
    }


    /**
     * 初始化Activity管理器
     *
     * @param application
     */
    public static void init(Application application, boolean debug) {
        if (application == null) {
            throw new IllegalArgumentException("Application is null");
        }
        ActivityLifecycleManager manager = get();
        if (!manager.isInit) {
            isDebug = debug;
            application.unregisterActivityLifecycleCallbacks(manager.mActivityLifecycleCallbacks);
            application.registerActivityLifecycleCallbacks(manager.mActivityLifecycleCallbacks);
        } else {
            throw new IllegalArgumentException("init repeatedly");
        }
    }


    /**
     * 关闭所有Activity
     *
     * @param content
     * @param cls     如果不为空，将会跳转到该Activity
     * @param bundle  附带参数
     */
    public void closeAllActivity(Context content, Class<? extends Activity> cls, Bundle bundle) {
        boolean exists = false;
        List<Activity> activities = mActivityLifecycleCallbacks.activities;
        for (int i = 0; i < activities.size(); i++) {
            Activity activity = activities.get(i);
            if (activity.getClass().equals(cls)) {
                exists = true;
            } else {
                activities.get(i).finish();
            }
        }
        if (!exists && cls != null) {
            Intent intent = new Intent(content, cls);
            intent.putExtras(bundle);
            content.startActivity(intent);
        }
    }


    /**
     * 关闭所有Activity
     *
     * @param content
     */
    public void closeAllActivity(Context content) {
        closeAllActivity(content, null, null);
    }


    /**
     * 获取栈顶的Activity
     *
     * @return
     */
    public Activity getTopActivity() {
        List<Activity> activities = mActivityLifecycleCallbacks.activities;
        return activities.size() == 0 ? null : activities.get(activities.size() - 1);
    }


    /**
     * 检查栈中是否存在指定类型的Activity
     *
     * @param cls
     * @return
     */
    public boolean exists(@NonNull Class<? extends Activity> cls) {
        for (int i = mActivityLifecycleCallbacks.activities.size() - 1; i >= 0; i++) {
            Activity activity = mActivityLifecycleCallbacks.activities.get(i);
            if (cls.isInstance(activity)) {
                return true;
            }
        }
        return false;
    }


    static class ActivityLifecycleCallbacksImpl implements Application.ActivityLifecycleCallbacks {

        private List<Activity> activities = new ArrayList<>();


        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            activities.add(activity);
            if (isDebug) {
                AppLog.d(TAG, String.format("activity created : %s", activity.getLocalClassName()));
            }
        }


        @Override
        public void onActivityStarted(Activity activity) {
            if (isDebug) {
                AppLog.d(TAG, String.format("activity started : %s", activity.getLocalClassName()));
            }
        }


        @Override
        public void onActivityResumed(Activity activity) {
            if (isDebug) {
                AppLog.d(TAG, String.format("activity resumed : %s", activity.getLocalClassName()));
            }
        }


        @Override
        public void onActivityPaused(Activity activity) {
            if (isDebug) {
                AppLog.d(TAG, String.format("activity paused : %s", activity.getLocalClassName()));
            }
        }


        @Override
        public void onActivityStopped(Activity activity) {
            if (isDebug) {
                AppLog.d(TAG, String.format("activity stopped : %s", activity.getLocalClassName()));
            }
        }


        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }


        @Override
        public void onActivityDestroyed(Activity activity) {
            activities.remove(activity);
            if (isDebug) {
                AppLog.d(TAG, String.format("activity destroyed : %s", activity.getLocalClassName()));
            }
        }
    }
}
